package _02_cous;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class ConsumerOne {

    public static void main(String[] args) throws MQClientException {
        //创建一个拉取消息的消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("rocketmq-consumer-one-group");
        //设置名字地址
        consumer.setNamesrvAddr("127.0.0.1:9876");

        //绑定消息的主题
        /**
         * topic 要订阅的主题
         * subExpression 表达式 这个表达式是用于消息过滤
         */
        consumer.subscribe("01-send-one", "*");
        //消费者监听处理消息方法
       /* consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    //System.out.println("消费线程:"+Thread.currentThread().getName()+",消息ID:"+msg.getMsgId()+",消息内容:"+new String(msg.getBody()));
                    System.out.println("消息的内容为" + new String(msg.getBody()) );
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });*/
       consumer.setMessageListener(new MessageListenerConcurrently() {
           public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
               for (MessageExt messageExt : list) {
                   System.out.println("消费线程:"+Thread.currentThread().getName()+",消息ID:"+messageExt.getMsgId()+",消息内容:"+new String(messageExt.getBody()));
               }
               //返回一个成功的状态 失败的话可以重试
               return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

               //下面代码 失败重试 成功提交成功
              /* try {
                   //增加积分
                   return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
               }catch (Exception e){
                   e.printStackTrace();
                   return ConsumeConcurrentlyStatus.RECONSUME_LATER;
               }*/

           }
       });

        //启动消费者
        consumer.start();
    }

}
